package controller;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.Custom;
import service.CustomService;
import service.impl.CustomServiceImpl;

// 当前的Servlet能处理所有关于custom表的业务
@WebServlet("/custom/*")
public class CustomServlet extends HttpServlet{
	// 创建服务
	CustomService service = new CustomServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.先得到最后一部分的请求路径  
		String path = req.getPathInfo();
		System.out.println(path);
		// 2.根据请求最后一部分路径，调用响应的业务
		switch(path) {
		case "/login": login(req,resp); break;
		case "/regist": regist(req,resp); break;
		}
	}

	public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.得到参数
		String name = req.getParameter("name");
		String pwd = req.getParameter("pwd");
		//2.请求登录的用户名和密码是散装的走
		Custom loginCustom = service.login(name,pwd);
		//3.登录成功返回的对象应该非空
		if (Objects.nonNull(loginCustom)) {
			// 把当前登录对象写入session
			HttpSession session = req.getSession(true);
			session.setAttribute("loginCustom", loginCustom);
			// 转发
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		}else {
			// 重定向到登录页面
			String basePath = this.getServletContext().getContextPath();
			resp.sendRedirect(basePath +"/login.jsp");
		}
	}
	
	public void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.获取参数
		String name = req.getParameter("name");
		String pwd = req.getParameter("pwd");
		//2.封装Custom
		Custom c = new Custom();
		c.setName(name);
		c.setPwd(pwd);  // 密码是文明的
		//3.调用服务，返回一个boolean结果
		boolean result = service.regist(c);
		//4.如果注册成功，转发登录页面给客户
		if (result) {
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}else {
			//如果失败了，重定向到注册页面
			String basePath = this.getServletContext().getContextPath();
			resp.sendRedirect(basePath +"/regist.jsp");
		}
	}
	


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
}
